
/**
 * Copyright (2024, ) Institute of Software, Chinese Academy of Sciences
 * author: wuheng@iscas.ac.cn
 * since:  0.1.0
 **/

use diesel::result::Error;
use serde_json::Value;
use diesel::sql_query;
use diesel::PgConnection;
use diesel::SqliteConnection;
use diesel::RunQueryDsl;

pub fn delete_sqlite3_object(conn: &mut SqliteConnection, table: &str, data: Value) -> Result<bool, Error> {
    let result = sql_query(generate_postgres_delete_object_sql(table))
        .bind::<diesel::sql_types::Text, _>(data["name"].as_str().unwrap())
        .bind::<diesel::sql_types::Text, _>(data["namespace"].as_str().unwrap())
        .bind::<diesel::sql_types::Text, _>(data["apigroup"].as_str().unwrap())
        .execute(conn)?;
    Ok(result > 0)
}

pub fn delete_postgres_object(conn: &mut PgConnection, table: &str, data: Value) -> Result<bool, Error> {
    let result = sql_query(generate_postgres_delete_object_sql(table))
        .bind::<diesel::sql_types::Text, _>(data["name"].as_str().unwrap())
        .bind::<diesel::sql_types::Text, _>(data["namespace"].as_str().unwrap())
        .bind::<diesel::sql_types::Text, _>(data["apigroup"].as_str().unwrap())
        .execute(conn)?;
    Ok(result > 0)
}

fn generate_postgres_delete_object_sql(table_name: &str) -> String {
    format!("DELETE FROM {} WHERE name = $1 AND namespace = $2 AND apigroup = $3;",
            table_name
    )
}

pub fn drop_postgres_table(conn: &mut PgConnection, table: &str) -> Result<bool, diesel::result::Error> {
    sql_query(generate_drop_table_sql(table)).execute(conn)?;
    Ok(true)
}

pub fn drop_sqlite3_table(conn: &mut SqliteConnection, table: &str) -> Result<bool, diesel::result::Error> {
    sql_query(generate_drop_table_sql(table)).execute(conn)?;
    Ok(true)
}

fn generate_drop_table_sql(table_name: &str) -> String {
    format!("DROP TABLE IF EXISTS {};",
            table_name
    )
}